package Thread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;

public class Demo29 {

    public static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock locker = new ReentrantLock(true);
        Semaphore semaphore = new Semaphore(1);
        //此时这里值为 1 的信号量，就相当于一个 “ 锁 ”，(二元信号量)

        //此处传入参数 true 表示“ 公平锁 ”
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
//                locker.lock();
                try {
                    semaphore.acquire();
                    count++;
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
//                locker.unlock();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
//                locker.lock();
                try {
                    semaphore.acquire();
                    count++;
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
//                locker.unlock();
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("count = " + count);
    }
}
